package com.etc.delivery.controller.appoint;

import com.etc.delivery.entity.Address;
import com.etc.delivery.entity.Appointment;
import com.etc.delivery.entity.Waybill;
import com.etc.delivery.service.appoint.IAppointmentService;
import com.etc.delivery.utils.ReadExcel;
import com.github.pagehelper.PageInfo;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@RequestMapping("/user")
@Controller
public class AppointmentController {

    @Resource
    private IAppointmentService iAppointmentService;


    @RequestMapping("/appoint")
    public ModelAndView appoint(Appointment appoin) {
        ModelAndView mv = new ModelAndView();
        boolean flag = iAppointmentService.appoint(appoin);
        if (flag) {
            mv.addObject("msg", "订单提交成功");
            mv.setViewName("redirect:index.jsp");
        } else {
            mv.addObject("msg", "余额不足,订单提交失败");
            mv.setViewName("forward:userRecharge.jsp");
        }
        return mv;
    }

    @RequestMapping("/showAllAppoint")
    public ModelAndView showAllAppoint() {
        ModelAndView mv = new ModelAndView();
        List<Appointment> applist = iAppointmentService.showAllAppoint();
        mv.addObject("applist", applist);
        mv.setViewName("forward:showAllAppoint.jsp");
        return mv;
    }

    @RequestMapping("/showAllAppointByPhone")
    public ModelAndView showAllAppointByPhone(String phone) {
        ModelAndView mv = new ModelAndView();
        List<Appointment> applist = iAppointmentService.showAllAppointByPhone(phone);
        mv.addObject("applist", applist);
        mv.setViewName("forward:showAllAppoint.jsp");
        return mv;
    }

    @RequestMapping("/showAllAppointByPhonePage")
    public ModelAndView showAllAppointByPhonePage(String phone, int pageNum, int pageSize) {
        PageInfo<Appointment> pageInfo = iAppointmentService.showAllAppointByPhonePage(phone, pageNum, pageSize);
        List<Appointment> applist = iAppointmentService.showAllAppointByPhone(phone);
        ModelAndView mv = new ModelAndView();
        mv.addObject("pageInfo", pageInfo);
        mv.addObject("applist", applist);
        mv.setViewName("forward:showAllAppoint.jsp");
        return mv;
    }

    @RequestMapping("/queryMoneyByType")
    @ResponseBody
    public double queryMoneyByType(int typeId) {
        return iAppointmentService.queryMoneyByType(typeId);
    }

    @RequestMapping("/deleteAppoin")
    public ModelAndView deleteAppoin(int waybill_no) {
        ModelAndView mv = new ModelAndView();

        boolean flag = iAppointmentService.deleteAppoin(waybill_no);
        if (flag) {
            mv.addObject("msg", "取消成功");
            mv.setViewName("forward:index.jsp");
        } else {
            mv.addObject("msg", "取消失败");
            mv.setViewName("forward:showAllAppoint.jsp");
        }
        return mv;
    }

    //导出excel
    @RequestMapping("/export")
    public void export(String phone, HttpServletResponse response) throws IOException {
        // 只是让浏览器知道要保存为什么文件而已，真正的文件还是在流里面的数据，你设定一个下载类型并不会去改变流里的内容。
        //而实际上只要你的内容正确，文件后缀名之类可以随便改，就算你指定是下载excel文件，下载时我也可以把他改成pdf等。

        response.setContentType("application/vnd.ms-excel");

        Date date = new Date();
        SimpleDateFormat smp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        // 传递中文参数编码
        String codedFileName = java.net.URLEncoder.encode("appoint" + smp.format(date), "UTF-8");
        response.setHeader("content-disposition", "attachment;filename=" + codedFileName + ".xls");

        List<Appointment> list = iAppointmentService.showAllAppointByPhone(phone);
        // 定义一个工作薄
        Workbook workbook = new HSSFWorkbook();
        // 创建一个sheet页
        Sheet sheet = workbook.createSheet("全部订单");
        // 创建一行
        Row row = sheet.createRow(0);
        // 在本行赋值 以0开始
        row.createCell(0).setCellValue("编号");
        row.createCell(1).setCellValue("类型");
        row.createCell(2).setCellValue("寄件人姓名");
        row.createCell(3).setCellValue("寄件人电话");
        row.createCell(4).setCellValue("寄件人地址");
        row.createCell(5).setCellValue("收件人姓名");
        row.createCell(6).setCellValue("收件人电话");
        row.createCell(7).setCellValue("收件人地址");
        row.createCell(8).setCellValue("价格");

        // 定义样式
        CellStyle cellStyle = workbook.createCellStyle();
        // 格式化日期
        //cellStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy"));
        // 遍历输出
        for (int i = 1; i <= list.size(); i++) {
            Appointment appointment = list.get(i - 1);
            row = sheet.createRow(i);
            row.createCell(0).setCellValue(appointment.getWaybill_no());
            row.createCell(1).setCellValue(appointment.getMail_type());
            row.createCell(2).setCellValue(appointment.getSender_name());
            row.createCell(3).setCellValue(appointment.getSender_phone());
            row.createCell(4).setCellValue(appointment.getSender_address());
            row.createCell(5).setCellValue(appointment.getRecipient_name());
            row.createCell(6).setCellValue(appointment.getRecipient_phone());
            row.createCell(7).setCellValue(appointment.getRecipient_address());
            row.createCell(8).setCellValue(appointment.getMail_cost());
        }
        OutputStream fOut = response.getOutputStream();
        workbook.write(fOut);
        fOut.flush();
        fOut.close();
    }

    //导出excel
    @RequestMapping("/export1")
    public void export1(String phone, HttpServletResponse response) throws IOException {
        // 只是让浏览器知道要保存为什么文件而已，真正的文件还是在流里面的数据，你设定一个下载类型并不会去改变流里的内容。
        //而实际上只要你的内容正确，文件后缀名之类可以随便改，就算你指定是下载excel文件，下载时我也可以把他改成pdf等。

        response.setContentType("application/vnd.ms-excel");

        Date date = new Date();
        SimpleDateFormat smp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        // 传递中文参数编码
        String codedFileName = java.net.URLEncoder.encode("appoint" + smp.format(date), "UTF-8");
        response.setHeader("content-disposition", "attachment;filename=" + codedFileName + ".xls");

        List<Appointment> list = iAppointmentService.showAllAppointByPhone(phone);
        // 定义一个工作薄
        Workbook workbook = new HSSFWorkbook();
        // 创建一个sheet页
        Sheet sheet = workbook.createSheet("多个订单");
        // 创建一行
        Row row = sheet.createRow(0);
        // 在本行赋值 以0开始
        row.createCell(0).setCellValue("类型");
        row.createCell(1).setCellValue("寄件人姓名");
        row.createCell(2).setCellValue("寄件人电话");
        row.createCell(3).setCellValue("寄件人地址");
        row.createCell(4).setCellValue("收件人姓名");
        row.createCell(5).setCellValue("收件人电话");
        row.createCell(6).setCellValue("收件人地址");
        row.createCell(7).setCellValue("");
        row.createCell(8).setCellValue("类型提示");
        row.createCell(9).setCellValue("1,日用品");
        row.createCell(10).setCellValue("2,衣物");
        row.createCell(11).setCellValue("3,文件");
        row.createCell(12).setCellValue("4,蔬果");

        // 定义样式
        CellStyle cellStyle = workbook.createCellStyle();

        OutputStream fOut = response.getOutputStream();
        workbook.write(fOut);
        fOut.flush();
        fOut.close();
    }

    private static Log log = LogFactory.getLog(AppointmentController.class);


    /**
     * 上传Excel,读取Excel中内容
     *
     * @param myfile
     * @param request
     * @param response
     * @return
     * @throws IOException
     */

    @RequestMapping(value = "/batchimport", method = RequestMethod.POST)
    public String batchimport(@RequestParam(value = "myfile") MultipartFile myfile,
                              HttpServletRequest request, HttpServletRequest response) throws IOException {
        log.info("ClientController ..batchimport() start");
        String Msg = null;
        boolean b = false;
        System.out.println("123123");
        //判断文件是否为空
        if (myfile == null) {
            Msg = "文件是为空！";
            request.getSession().setAttribute("msg", Msg);
            return "client/client";
        }

        //获取文件名
        String name = myfile.getOriginalFilename();
        System.out.println(name);
        //进一步判断文件是否为空（即判断其大小是否为0或其名称是否为null）验证文件名是否合格
        long size = myfile.getSize();
        if (name == null || ("").equals(name) && size == 0) {
            Msg = "文件格式不正确！请使用.xls或.xlsx后缀文档。";
            request.getSession().setAttribute("msg", Msg);
            return "client/client";
        }

        //创建处理EXCEL
        ReadExcel readExcel = new ReadExcel();
        //解析excel，获取客户信息集合。
        List<Waybill> dataList = readExcel.getExcelInfo(myfile);
        System.out.println(dataList);
        if (dataList != null && !dataList.toString().equals("[]") && dataList.size() >= 1) {
            b = true;
        }

        iAppointmentService.add(dataList);

        if (b) {

            //迭代添加客户信息（注：实际上这里也可以直接将UserList集合作为参数，在Mybatis的相应映射文件中使用foreach标签进行批量添加。）
            for (Waybill User : dataList) {
                //这里可以做添加数据库的功能
                System.out.println("第一个值：" + User.getMailType() + "\t第二个值：" + User.getSenderName());
            }
            Msg = "批量导入EXCEL成功！";
            request.getSession().setAttribute("msg", Msg);
        } else {
            Msg = "批量导入EXCEL失败！";
            request.getSession().setAttribute("msg", Msg);
        }
        return "user/index";
    }

    @RequestMapping(value = "queryProvince")
    @ResponseBody
    public List<Address> queryProvince() {
        return iAppointmentService.queryProvince();
    }

    @RequestMapping(value = "queryCity")
    @ResponseBody
    public List<Address> queryCity(Integer id) {
        return iAppointmentService.queryCity(id);
    }
}
